package com.le.tester.book.effectivejava3rdchinese.articleSeventyEight;

import com.github.javafaker.Bool;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * createTime：2022/10/7 11:09
 * description：使用线程的ThreadStop
 */
public class StopThread {

    private static volatile Boolean stopRequested = Boolean.FALSE;

    //private static volatile int nextSerialNumber = 0;

    private static final AtomicLong nextSerialNum = new AtomicLong();

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(() -> {
            int i = 0;
            while (!stopRequested)
                //不是原子性的操作，然后在需要同步的时候，并不能同步
                //增加原子性的必要性
                i++;
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        //stopRequested = Boolean.TRUE;
        //读和写都是同步的，保证同步可以起到作用,一般volatile和synchronized同时使用，可以保证同步和可见性
        setStopRequested();

    }

    //同步读
    private static synchronized Boolean getStopRequested() {
        return stopRequested;
    }

    //同步写
    private static synchronized void setStopRequested() {
        stopRequested = true;
    }

    public static long generateSerialNumber() {
        //++操作不属于原子性的操作，那么这边警告了non-atomic
        //return nextSerialNumber++;
       return nextSerialNum.incrementAndGet();
    }
}
